package com.cfx.exercise_41;

import java.awt.AWTException;
import java.awt.EventQueue;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Clock;
import java.util.Calendar;

import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.border.TitledBorder;
import java.awt.Font;  
  
public class ShutWindow extends JFrame {  
  
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel contentPane;  
    private JTextField textField_time;  
    private JTextField textField_show;  
    private JTextField textField_delay;  
    private JTextField textField_3;  
    private JTextField txthhmm;  
    private JRadioButton rdbtn_today;  
    private JRadioButton rdbtn_tomorrow;  
    private ShutDownTool sd = new ShutDownTool();  
    private final ButtonGroup buttonGroup = new ButtonGroup();  
  
    /** 
     * Launch the application. 
     */  
    public static void main(String[] args) {  
        EventQueue.invokeLater(new Runnable() {  
            public void run() {  
                try {  
                	ShutWindow frame = new ShutWindow();  
                    frame.showIcon();  
                    frame.setVisible(true);  
                      
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        });  
    }  
    /** 
     * 显示系统托盘 
     */  
    public static void showIcon(){  
        if(SystemTray.isSupported()){//判断系统是否托盘  
            //创建一个托盘图标对象  
            TrayIcon icon =   
            new TrayIcon(Toolkit.getDefaultToolkit().getImage(Clock.class.getResource("/images/21.png")),"ShutDown for Windows");  
//          TrayIcon icon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(Clock.class.getResource("/javax/swing/plaf/basic/icons/JavaCup16.png")));  
            //创建弹出菜单  
            PopupMenu menu = new PopupMenu();  
            //添加一个用于退出的按钮  
            MenuItem item = new MenuItem("退出");  
            item.addActionListener(new ActionListener() {  
                public void actionPerformed(ActionEvent e) {  
                    System.exit(0);  
                }  
            });  
            menu.add(item);  
            //添加弹出菜单到托盘图标  
            icon.setPopupMenu(menu);  
            SystemTray tray = SystemTray.getSystemTray();//获取系统托盘  
            try {  
                tray.add(icon);  
            } catch (AWTException e1) {  
                // TODO Auto-generated catch block  
                e1.printStackTrace();  
            }//将托盘图表添加到系统托盘  
        }  
      
    }  
    /** 
     * 设置窗口图标 
     */  
    public void setWindowIcon()  
    {  
        ImageIcon imageIcon = new ImageIcon(getClass().getResource("/images/icon.png"));  
        this.setIconImage(imageIcon.getImage());  
    }  
      
      
    /** 
     * Create the frame. 
     */  
    private ShutWindow() {
    	setFont(new Font("叶根友毛笔行书2.0版", Font.BOLD, 13));
    	setForeground(Color.GREEN);  
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        setBounds(100, 100, 450, 300);  
        this.setTitle("定时关机软件");  
        setWindowIcon();  
        JMenuBar menuBar = new JMenuBar();  
        setJMenuBar(menuBar);  
          
        JMenu menu = new JMenu("\u5F00\u59CB");  
        menuBar.add(menu);  
          
        JMenuItem menuItem_1 = new JMenuItem("\u9000\u51FA");  
        menuItem_1.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent arg0) {  
                 if (JOptionPane.showConfirmDialog(null, "确定退出?") == 0) {  
                      System.exit(0);  
                     }  
            }  
        });  
        menu.add(menuItem_1);  
          
        JMenu menu_1 = new JMenu("\u5E2E\u52A9");  
        menuBar.add(menu_1);  
          
        JMenuItem menuItem = new JMenuItem("\u5173\u4E8E");  
        menuItem.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e) {  
                JOptionPane.showMessageDialog(null, "Author：zhangshuo \nVersion：1.0\nTime: 2017.3 SDU\nContact:  15824515731@163.com", "关于", JOptionPane.PLAIN_MESSAGE);  
  
            }  
        });  
        menu_1.add(menuItem);  
        contentPane = new JPanel();  
        contentPane.setBackground(Color.PINK);
        contentPane.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));  
        setContentPane(contentPane);  
        contentPane.setLayout(null);  
          
        textField_time = new JTextField();  
        textField_time.setBounds(184, 55, 66, 21);  
        contentPane.add(textField_time);  
        textField_time.setColumns(10);  
          
        textField_show = new JTextField();  
        textField_show.setEditable(false);  
        textField_show.setBounds(72, 153, 311, 21);  
        contentPane.add(textField_show);  
        textField_show.setColumns(10);  
        textField_show.setText("提示：当前无定时关机计划");  
          
        JButton button_cancel = new JButton("\u53D6\u6D88\u5B9A\u65F6\u5173\u673A");  
        button_cancel.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e) {  
                shutDownCancel();  
            }  
        });  
        button_cancel.setBounds(260, 184, 123, 23);  
        contentPane.add(button_cancel);  
          
        JButton button_set_time = new JButton("\u8BBE\u5B9A\u5173\u673A\u65F6\u95F4");  
        button_set_time.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent arg0) {  
                shutDownAt();  
            }  
        });  
        button_set_time.setBounds(260, 54, 123, 23);  
        contentPane.add(button_set_time);  
          
        textField_delay = new JTextField();  
        textField_delay.setBounds(72, 101, 102, 21);  
        contentPane.add(textField_delay);  
        textField_delay.setColumns(10);  
          
        JButton button_set_delay = new JButton("\u786E\u5B9A");  
        button_set_delay.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e) {  
                shutDownDelay();  
            }  
        });  
        button_set_delay.setBounds(260, 100, 123, 23);  
        contentPane.add(button_set_delay);  
          
        textField_3 = new JTextField();  
        textField_3.setEditable(false);  
        textField_3.setText("\u5206\u949F\u540E\u5173\u673A");  
        textField_3.setBounds(184, 101, 66, 21);  
        contentPane.add(textField_3);  
        textField_3.setColumns(10);  
          
        txthhmm = new JTextField();  
        txthhmm.setEditable(false);  
        txthhmm.setText("\u5173\u673A\u65F6\u95F4:(hh:mm)");  
        txthhmm.setBounds(72, 55, 102, 21);  
        contentPane.add(txthhmm);  
        txthhmm.setColumns(10);  
          
        rdbtn_today = new JRadioButton("\u4ECA\u5929");  
        rdbtn_today.setSelected(true);  
        buttonGroup.add(rdbtn_today);  
        rdbtn_today.setBounds(72, 25, 59, 23);  
        contentPane.add(rdbtn_today);  
          
        rdbtn_tomorrow = new JRadioButton("\u660E\u5929");  
        buttonGroup.add(rdbtn_tomorrow);  
        rdbtn_tomorrow.setBounds(133, 25, 66, 23);  
        contentPane.add(rdbtn_tomorrow);  
    }  
    /** 
     * n分钟后关机 
     */  
    public void shutDownDelay(){  
        String min = textField_delay.getText();  
        if(min.equals("")){  
            textField_show.setText("输入为空...");  
            return;  
        }  
        for (int i = 0; i < min.length(); i++) {  
            if(!Character.isDigit(min.charAt(i))){  
                textField_show.setText("输入数据不合法,请输入数字");  
                return;  
            }  
        }  
        int min1 = Integer.parseInt(min);  
        if(min1>24*60*2){  
            textField_show.setText("延迟关机时间不能超过2天（2880分钟）");  
            return;  
        }  
        if(min1==0) {  
              
            int res= JOptionPane.showConfirmDialog(null, "马上关机，确定吗？","确认", JOptionPane.YES_NO_OPTION);  
            if(res==0){}  
//              JOptionPane.showMessageDialog(null, "关机", "标题条文字串", JOptionPane.ERROR_MESSAGE);  
            else{  
//              JOptionPane.showMessageDialog(null, "取消了", "标题条文字串", JOptionPane.ERROR_MESSAGE);  
                return;  
            }  
        }  
          
        int sec = Integer.parseInt(min)*60;  
        int res= JOptionPane.showConfirmDialog(null, min+"分钟后关机， 确定吗?","确认", JOptionPane.YES_NO_OPTION);  
        if(res==0){}  
        else{  
            return;  
        }  
          
        sd.shutDownS(sec);  
        textField_show.setText("提示："+min+"分钟后关机！");  
        textField_delay.setText("");  
    }  
      
    /** 
     * 在hh:mm时间关机 
     */  
    public void shutDownAt(){  
        String time = this.textField_time.getText();  
          
        if(time.length()!=5){  
            textField_show.setText("输入时间格式超长");  
            return ;  
        }  
        if (!time.matches("([0-9]{2}):([0-9]{2})") && !time.matches("([0-9]{2})：([0-9]{2})") ){  
            textField_show.setText("输入时间格式不正确");  
            return ;  
        }  
          
        if(time.equals("")){  
            textField_show.setText("输入为空...");    
            return;  
        }  
        int hh = Integer.parseInt(time.substring(0,2));  
        int mm= Integer.parseInt(time.substring(3,5));  
        if(hh>=24 || hh<0){  
            textField_show.setText("小时要在0-23之间");  
            return;  
        }  
        if(mm>=60 || mm<0){  
            textField_show.setText("分钟要在0-59之间");  
            return;  
        }  
        Calendar c = Calendar.getInstance();//可以对每个时间域单独修改  
        int hour = c.get(Calendar.HOUR_OF_DAY);   
        int minute = c.get(Calendar.MINUTE);   
          
        int today=1;  
        if(rdbtn_today.isSelected()){  
            today=1;  
        }  
        else if(rdbtn_tomorrow.isSelected()){  
            today=0;  
        }  
        if(today==1 && hh<hour || today==1 && hh==hour && mm<minute ){  
            textField_show.setText("输入的今天时间要在当前时间之后");  
            return;  
        }  
          
        if(today==1 && hour==hh && minute==mm){  
            int res= JOptionPane.showConfirmDialog(null, "马上关机，确定吗？","确认", JOptionPane.YES_NO_OPTION);  
            if(res==0){}  
//              JOptionPane.showMessageDialog(null, "关机", "提示", JOptionPane.ERROR_MESSAGE);  
            else{  
//              JOptionPane.showMessageDialog(null, "取消", "提示", JOptionPane.ERROR_MESSAGE);  
                return;  
            }  
        }  
          
          
        String str1 = today==1?"今天":"明天";  
        String s="提示：将在"+str1+time+"关机！";  
          
        int res= JOptionPane.showConfirmDialog(null, s+" 确定吗?","确认", JOptionPane.YES_NO_OPTION);  
        if(res==0){}  
        else{  
            return;  
        }  
          
        this.sd.shutDownAt(time, today);  
        textField_show.setText(s);  
        textField_time.setText("");  
    }  
    /** 
     * 取消定时关机计划 
     */  
    public void shutDownCancel(){  
        sd.shutDownCancel();  
        textField_show.setText("提示：已取消定时关机计划");  
    }  
}  